package com.hs.shirodemo01.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hs.shirodemo01.exception.ProjectException;
import com.hs.shirodemo01.pojo.TbPermission;
import com.hs.shirodemo01.service.TbPermissionService;
import com.hs.shirodemo01.utils.Constant;
import com.hs.shirodemo01.utils.Result;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 郭敖
 * @since 2023-08-18
 */
@RestController
@RequestMapping("/permissions")
public class TbPermissionController {
    @Autowired
    private TbPermissionService service;

    @RequiresPermissions("permission:select")
    @GetMapping("/permission")
    public Result findAllPermissions() {
        return Result.success();
    }

    @RequiresPermissions("permission:select")
    @GetMapping("/page/{pageNum}/{pageSize}")
    public Result findByPage(@PathVariable Integer pageNum, @PathVariable Integer pageSize){
        Page<TbPermission> page = service.findByPage(pageNum, pageSize);
        HashMap<String,Object> map = new HashMap<>();
        map.put("list", page.getRecords());
        map.put("total",page.getTotal());
        map.put("totalPage",page.getPages());
        return Result.success(map);
    }

    @RequiresPermissions("permission:select")
    @GetMapping("/permission/select/{id}")
    public Result findPermissionById(@PathVariable Integer id){
        TbPermission permission = service.getById(id);
        return Result.success(permission);
    }

    @RequiresPermissions("permission:add")
    @PostMapping("/insertPermission")
    public Result insertPermission(@RequestBody TbPermission permission){
        if(!service.save(permission)){
            throw  new ProjectException(Constant.CREATED_ERR.getMsg(),Constant.CREATED_ERR.getCode());
        }
        return Result.success();
    }

    @RequiresPermissions("permission:update")
    @PutMapping("/updatePermission")
    public Result updatePermission(@RequestBody TbPermission permission){
        if(!service.updateById(permission)){
            throw new ProjectException(Constant.UPDATE_ERR.getMsg(), Constant.UPDATE_ERR.getCode());
        }
        return Result.success();
    }

    @RequiresPermissions("permission:delete")
    @DeleteMapping("/removePermission/{id}")
    public Result removeById(@PathVariable Integer id){
        if(service.removeById(id)){
            throw new ProjectException(Constant.DELETED_ERR.getMsg(), Constant.UPDATE_ERR.getCode());
        }
        return Result.success();
    }
}

